<template>
  <el-dialog
          :model-value="visible"
          title="编辑"
          @close="dialogClose"
          width="40%"
  >
     <el-form :model="row" ref="formRef" :rules="formRules" label-width="100px">
        <el-form-item label="故障名称：" prop="name">
          <el-input v-model="row.name"></el-input>
        </el-form-item>
        <el-form-item label="故障状态：" prop="status">
           <el-radio-group v-model="row.status">
              <el-radio border :label='1' >处理中</el-radio>   <!-- label是字符串，:label是数字-->
              <el-radio border :label='2' >已关闭</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="故障等级：" prop="grade">
           <el-radio-group v-model="row.grade">
              <el-radio border :label='1' >一级</el-radio>   <!-- label是字符串，:label是数字-->
              <el-radio border :label='2' >二级</el-radio>
              <el-radio border :label='3' >三级</el-radio>
              <el-radio border :label='4' >四级</el-radio>
              <el-radio border :label='5' >五级</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="处理人员：" prop="user">
           <el-select class="m-2" filterable multiple v-model="row.user" @click="getUser" placeholder="请选择">
            <el-option v-for="row in user" :key="row.id" :label="row.first_name" :value="row.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故障报告：" prop="file">
            <el-upload
              :limit="1"
              v-model:file-list="fileList"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">上传文件</el-button>
              </template>
            </el-upload>
<!--            <el-link :href="row.upload" type="primary" style="margin-left: 20px; margin-bottom: 12px">报告下载</el-link>-->
           <el-button type="primary" text  @click="downFile" style="margin-left: 20px; margin-bottom: 12px">报告下载</el-button>
        </el-form-item>
        <el-form-item label="开始时间：" prop="start_time">
             <el-date-picker v-model="row.start_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间：" prop="end_time">
            <el-date-picker v-model="row.end_time" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="故障原因：" prop="reason">
          <el-input v-model="row.reason" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="故障总结：" prop="summarize">
          <el-input v-model="row.summarize" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>

  </el-dialog>
</template>

<script>
    export default {
        props: {
            visible: Boolean,
            row: '',  // 当前行内容
        },
        data() {
            return {
                fileList : [],
                user: '',
                formRules: {
                    name: [
                        {required: true, message: '请输入故障名称', trigger: 'blur'},
                        {min: 2, message: '事件名称长度应不小于2个字符', trigger: 'blur'}
                    ],
                   status: [
                      {required: true, message: '请选择故障状态', trigger: 'blur'},
                   ],
                   grade: [
                      {required: true, message: '请选择故障等级', trigger: 'blur'},
                   ],
                   user: [
                      {required: true, message: '请选择处理人员', trigger: 'blur'},
                   ],
                },
            }
        },
        methods: {
          dialogClose() {
            this.$emit('update:visible', false); // 当对话框关闭，通过父组件更新为false
            this.$parent.getData();
          },
          getUser() {
            this.$http.get('/config/user/?page_size=50')
                .then(res => {
                    this.user = res.data.data;
                });
            },
          //处理下载文件，携带token
          downFile() {
             this.$http({
                  method: 'get',
                  url: '/fault_down_file/'+ '?file=' + this.row.upload,
                  responseType: 'blob' // 告诉axios我们期望得到一个blob响应
                })
                  .then(res => {
                      // 响应体response.data已经是Blob对象
                      const blob = res.data;
                      // 创建一个a标签用于下载
                      let link = document.createElement('a');
                      link.href = URL.createObjectURL(blob);
                      // 设置下载文件的名称，这里假设this.row.upload是文件名（包括扩展名）
                      link.setAttribute('download', this.row.upload);
                       // 模拟点击进行下载
                      link.click();
                      //清理
                      link = null;
                  })
             },
          submit() {
            this.$refs.formRef.validate((valid) => {
              if (valid) {
                 if(!this.fileList.length) {
                    this.$message.warning('请上传文件')
                    return
                   };
                  let fd = new FormData();
                  fd.append("file", this.fileList[0].raw);
                  fd.append('name', this.row.name);
                  fd.append('status', this.row.status);
                  fd.append('grade', this.row.grade);
                  fd.append('start_time', this.row.start_time);
                  fd.append('end_time', this.row.end_time);
                  fd.append('user', this.row.user);
                  fd.append('reason', this.row.reason);
                  fd.append('summarize', this.row.summarize);
                this.$http.put('/tools/fault/' + this.row.id + '/', fd)
                  .then(res => {
                    if (res.data.code == 200){
                      this.$message.success('修改成功');
                      this.dialogClose()  // 关闭窗口
                    }
                  })
              } else {
                this.$message.error('格式错误！')
              }
            })
          },
        },
        watch: {
             visible() {
                if(this.visible){  // 关闭窗口不请求
                    const user = this.row.user;
                    this.row.user = []; // [1,5,3]
                    for(let i in user) {
                        this.row.user.push(user[i].id)
                    }

                    this.getUser();
                }
            }
        }
    }
</script>

<style scoped>

</style>